package com.isoft.c2team3service2.controller;

import cn.hutool.core.util.StrUtil;
import com.isoft.c2team3service2.bean.ResponseData;
import com.isoft.c2team3service2.dto.MemberBuyDTO;
import com.isoft.c2team3service2.dto.PostDTO;
import com.isoft.c2team3service2.entity.Person;
import com.isoft.c2team3service2.entity.Post;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.service.MemberService;
import com.isoft.c2team3service2.service.PostService;
import com.isoft.c2team3service2.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static com.isoft.c2team3service2.util.RedisConstants.USER_LOGIN_KEY;

@RestController
@RequestMapping("/member")
public class MemberController extends BaseController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private PostService postService;

    /**
     * 1. 创建会员订单（用户开通会员）- 需要登录
     */
    @PostMapping("/buy")
    public ResponseData<Map<String, Object>> buyMember(@RequestBody MemberBuyDTO buyDTO) {
        UserDTO loginUser = UserHolder.getUser();
        System.out.println("MemberController获取的UserDTO：id=" + loginUser.getId() + ", email=" + loginUser.getEmail());

        // 关键修复：若email为空，从Redis手动查询补充
        if (StrUtil.isBlank(loginUser.getEmail())) {
            String token = request.getHeader("Authorization").replace("Bearer ", "");
            String redisKey = USER_LOGIN_KEY + token;
            // 从Redis直接获取email
            String email = stringRedisTemplate.opsForHash().get(redisKey, "email").toString();
            loginUser.setEmail(email); // 手动设置email
            System.out.println("补充后的email：" + email);
        }

        if (loginUser == null) {
            return new ResponseData<>(401, "请先登录", null);
        }

        try {
            Map<String, Object> result = memberService.createMemberOrder(buyDTO, loginUser.getId(), loginUser.getEmail());
            // 优化提示文案：明确“已支付”
            return new ResponseData<>(200, "会员开通成功，订单已自动支付", result);
        } catch (RuntimeException e) {
            return new ResponseData<>(500, e.getMessage(), null);
        }
    }

    /**
     * 2. 查询用户会员状态 - 需要登录
     */
    @GetMapping("/status")
    public ResponseData<Person> getMemberStatus() {
        UserDTO loginUser = UserHolder.getUser();
        if (loginUser == null) {
            return new ResponseData<>(401, "请先登录", null);
        }

        Person person = memberService.getUserMemberStatus(loginUser.getEmail());
        return resultT(person, "会员状态查询");
    }

    /**
     * 3. 支付回调接口（第三方支付平台调用，如支付宝/微信支付）
     * 注意：实际需加签名验证（防止伪造回调）
     */
    @PostMapping("/pay/callback")
    public String payCallback(
            @RequestParam("orderNo") String orderNo,
            @RequestParam("payStatus") Integer payStatus) {
        if (StrUtil.isBlank(orderNo) || payStatus == null) {
            return "fail";
        }
        // 调用业务层处理回调
        return memberService.handlePayCallback(orderNo, payStatus);
    }

    //会员发送贴子
    @PostMapping("/pay/createPost")
    public ResponseData<PostDTO> createPost(
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam("isPaid") Integer isPaid,
            // 新增：接收前端传递的isPrivate（默认0，允许传递1）
            @RequestParam(value = "isPrivate", defaultValue = "0") Integer isPrivate,
            BigDecimal price)
    {
        boolean success = memberService.createPost(file, title, content, isPaid,isPrivate, price);
        if (success) {
            Integer userId = UserHolder.getUser().getId();
            List<PostDTO> userPosts = postService.findByUserId(userId);
            PostDTO createdPost = userPosts.isEmpty() ? null : userPosts.get(0);
            return resultT(createdPost, "创建帖子");
        } else {
            return resultT(null, "创建帖子（可能因付费/私密状态冲突或价格无效/涉及敏感字段）");
        }
    }
}